package com.akk.config;

import com.akk.config.annotation.IgnoreAuth;
import com.akk.exception.RestBusinessException;
import com.akk.utils.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.UUID;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        IgnoreAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else{
            return true;
        }
        //如果有@IgnoreAuth注解，则不验证
        if(annotation != null){
            return true;
        }

        HttpSession httpSession = request.getSession();
        String sessionValue = (String) httpSession.getAttribute(Constants.WEB_USER_TOKEN_KEY);

        if (sessionValue != null) {
            String[] strs = sessionValue.split("&&");
            String userId = strs[1];
            httpSession.setMaxInactiveInterval(60*30);
            httpSession.setAttribute(Constants.WEB_USER_TOKEN_KEY, UUID.randomUUID()+"&&"+userId);
            request.setAttribute(Constants.WEB_USER_KEY,userId);
            return true;

        } else {
            throw new RestBusinessException("会话超时，请重新登录.");
        }
    }
}
